/* components */
import BizCallCenterPhone from '@src/component/business/BizCallCenterPhone/BizCallCenterPhone.tsx'
import BizModifyPlanTime from '@src/component/business/BizModifyPlanTime/BizModifyPlanTime.tsx'
import UiTaskState from '@src/component/ui/UiTaskState/UiTaskState.tsx'
import CalendarPlanTimeDialog from '@src/modules/task/view/components/CalendarPlanTimeDialog.vue'
/* enum */
import ComponentNameEnum from '@model/enum/ComponentNameEnum'
import DateFormatEnum from '@model/enum/DateFormatEnum'
import {TaskFieldNameMappingEnum} from '@model/enum/FieldMappingEnum'
/* entity */
import Field from '@model/entity/Field'
import TaskType from '@model/entity/TaskType'
import TaskConfig from '@model/config/TaskConfig'
import Auth from '@model/entity/Auth'
/* vue */
import VC from '@model/VC'
import {Component, Emit, Prop} from 'vue-property-decorator'
import {CreateElement, VNode} from 'vue'
/* util */
import {openTabForCustomerView, openTabForTaskView} from '@src/util/business/openTab'
import {fmt_address} from '@src/filter/fmt'
import { formatDate, isEmpty } from 'pub-bbx-utils'
import Log from '@src/util/log.ts'
import { isCalendar } from '@src/util/CalendarUtil'
import { getRootWindowInitData } from '@src/util/window'
/* service */
import AuthService from '@service/AuthService'
/* scss */
import '@src/modules/task/components/TaskAllotModal/TaskMapInfoWindow/TaskMapInfoWindow.scss'
/* service */
import { allowModifyPlanTimeJudgeHandler } from '@service/TaskService'
import i18n from '@src/locales'

/* 工单地图信息弹窗数据 */
class TaskMapInfoData {
  address = {}
  customerName: string = ''
  customerId: string = ''
  description: string = ''
  isTimeout: boolean = false
  linkMan: { name?: string, phone?: string } = { name: '', phone: '' }
  planTime: string = ''
  serviceType: string = ''
  serviceContent: string = ''
  taskId: string = ''
  taskNo: string = ''
  planStartTimeShow: boolean = false
  planEndTimeShow: boolean = false
  planStartTime: string = ''
  planEndTime: string = ''
  
  constructor(data: any = {}) {
    this.address = data?.address || data?.taddress || {}
    this.customerName = data?.customerName || data?.customer?.name || data?.customerEntity?.name || ''
    this.customerId = data?.customer?.id || data?.customerEntity?.id || ''
    this.description = data?.description || ''
    this.isTimeout = data?.isTimeout || false
    this.linkMan = data?.linkMan || data.linkman || { name: data.tlmName, phone: data.tlmPhone }
    this.planTime = data?.planTime || ''
    this.serviceType = data?.serviceType || ''
    this.serviceContent= data?.serviceContent || ''
    this.taskId = data?.taskId || data?.id || data?.taskUUID || ''
    this.taskNo = data?.taskNo || ''
    this.planStartTimeShow = data?.planStartTimeShow || false
    this.planEndTimeShow = data?.planEndTimeShow || false
    this.planStartTime = data?.planStartTime || ''
    this.planEndTime = data?.planEndTime || ''
  }
}

enum TaskMapInfoWindowEmitEventNameEnum {
  Close = 'close',
  PlanTimeChange = 'planTimeChange',
  UpdateCalendarPlanTime = 'updateCalendarPlanTime',
}

@Component({
  name: ComponentNameEnum.TaskMapInfoWindow,
  components: {
    BizCallCenterPhone,
    BizModifyPlanTime,
    UiTaskState,
    CalendarPlanTimeDialog
  }
})
export default class TaskMapInfoWindow extends VC {
  @Prop({ default: true }) readonly allowCustomerAuth: boolean | undefined
  /* 是否允许发送短信 */
  @Prop({ default: true }) readonly enableSendSms: boolean | undefined
  /* 计划时间字段 */
  @Prop() planTimeField: Field | undefined
  /* 是否显示 */
  @Prop({ default: true }) show: boolean | undefined
  /* 是否显示修改计划时间 */
  @Prop({ default: false }) showModifyPlanTime: boolean | undefined
  /* 是否显示关闭按钮 */
  @Prop({ default: true }) showCloseButton: boolean | undefined
  /* 工单信息 */
  @Prop() task: any | undefined
  /* 工单信息 */
  @Prop() taskType: TaskType | undefined
  /* 工单配置 */
  @Prop({ default: () => ({}) }) taskConfig: TaskConfig | undefined
  /* 渲染工单地图详细信息弹窗头部 */
  @Prop() renderTaskMapInfoWindowHeader: Function | undefined
  
  /* 工单地图信息弹窗数据 */
  get taskMapInfoData(): TaskMapInfoData {
    return new TaskMapInfoData(this.task)
  }
  
  /* 工单类型字段列表 */
  get taskTypeFields(): any {
    return this.taskType?.field || {}
  }
  
  /* 是否存在服务内容字段 */
  get isHaveServiceContentField(): boolean {
    return this.existsField(TaskFieldNameMappingEnum.ServiceContent)
  }
  
  /* 是否存在服务类型字段 */
  get isHaveServiceTypeField(): boolean {
    return this.existsField(TaskFieldNameMappingEnum.ServiceType)
  }
  
  /* 是否存在优先级字段 */
  get isHaveLevelField(): boolean {
    return this.existsField(TaskFieldNameMappingEnum.Level)
  }
  
  get globalRootWindowInitData() {
    return getRootWindowInitData()
  }
  
  /** 
   * @description 全局登录用户权限
  */
  get globalLoginUserAuth(): Auth {
    return (this.globalRootWindowInitData?.user?.auth || {}) as Auth
  }
  
  get globalIsHaveTaskViewDetailAuth() {
    return AuthService.isHaveTaskViewDetailAuth(this.globalLoginUserAuth)
  }
  
  /** 
   * @description 计划时间修改完成事件
  */
  @Emit(TaskMapInfoWindowEmitEventNameEnum.PlanTimeChange)
  private planTimeChangedHandler(planTime: string) {
    Log.succ(Log.Start, `TaskMapInfoWindow -> ${this.planTimeChangedHandler.name}`)
    return planTime
  }

  /** 
   * @description 修改计划开始时间完成事件
  */
  @Emit(TaskMapInfoWindowEmitEventNameEnum.UpdateCalendarPlanTime)
  private calendarPlanTimeChangedHandler(newCalendarTime: object) {
    Log.succ(Log.Start, `TaskMapInfoWindow -> ${this.calendarPlanTimeChangedHandler.name}`)
    return newCalendarTime;
  }
  
  /**
   * @description 关闭弹窗
   */
  @Emit(TaskMapInfoWindowEmitEventNameEnum.Close)
  private closedHandler() {
    Log.succ(Log.Start, `TaskMapInfoWindow -> ${this.closedHandler.name}`)
  }
  
  private customerViewJump(customerId: string): void {
    if (!this.allowCustomerAuth) return
    
    openTabForCustomerView(customerId)
  }
  
  /**
   * @description 是否存在某个字段
   */
  private existsField(fieldName: TaskFieldNameMappingEnum) {
    // 是否存在
    let isExists: boolean = false
    try {
      let field: any
      for (let index in this.taskTypeFields) {
        // 字段
        field = this.taskTypeFields[index]
        // 是否相等
        isExists = field?.name === fieldName
        if (isExists) break
      }
    } catch (error) {
      isExists = false
      Log.error(error, this.existsField.name)
    }
    
    return isExists
  }
  
  /**
   * @description 渲染提示通用字段
   * @param {Boolean} show 是否显示
   * @param {String} fieldName 字段名称
   * @param {String} value 字段值
   */
  private renderSystemField(show: boolean, fieldName: string, value: string): VNode | null {
    if (!show) return null
    
    let isEmptyValue = isEmpty(value)
    let valueDom = <span>{ value || '' }</span>
    
    return (
      <p>
        <label>{fieldName}：</label>
        {
          isEmptyValue
            ? valueDom
            : (
              <el-tooltip content={value} placement='top'>
                {valueDom}
              </el-tooltip>
            )
        }
      </p>
    )
  }

  /**
   * @description 计划开始时间
   * @param {String} planStartTime 字段值
   */
  private renderPlanStartDate(planStartTime: string): VNode | null {
    return (
      <p class='map-task-content-window-header-plantime'>
        <label>{i18n.t('common.form.type.planStartTime')}：</label>
        <span>{ formatDate(planStartTime, DateFormatEnum.YTMHMS) || '--' }</span>
      </p>
    )
  }

  /**
   * @description 计划完成时间
   * @param {String} planEndTime 字段值
   */
  private renderPlanEndDate(planEndTime: string): VNode | null {
    return (
      <p class='map-task-content-window-header-plantime'>
        <label>{i18n.t('common.form.type.planEndTime')}：</label>
        <span>{ formatDate(planEndTime, DateFormatEnum.YTMHMS) || '--' }</span>
      </p>
    )
  }

  /**
   * @description 渲染计划开始完成时间
   * @param {String} planEndTime 字段值
   */
  private renderCalendarDate(): VNode | null {
    
    const {
      planStartTimeShow = false,
      planEndTimeShow = false,
      planStartTime = '',
      planEndTime = ''
    } = this.taskMapInfoData;
    const isShow = planStartTimeShow || planEndTimeShow || false;

    return (
      <div class="map-task-calendar-time">
        <div>
          { planStartTimeShow && this.renderPlanStartDate(planStartTime) }
          { planEndTimeShow && this.renderPlanEndDate(planEndTime) }
        </div>
        { isCalendar && isShow && 
          <biz-modify-plan-time
          enableSendSms={this.enableSendSms}
          modifiable={allowModifyPlanTimeJudgeHandler(this.task)}
          task={this.task}
          onSuccess={(newCalendarTime: object) => this.calendarPlanTimeChangedHandler(newCalendarTime)}
        />
        }
      </div>
    )
  }
  /**
   * @description 渲染计划时间
   * @param {String} planTime 字段值
   */
  private renderPlanDate(planTime: string): VNode | null {
    return (
      <p class='map-task-content-window-header-plantime jus-bet'>
        <div>
          <label>{i18n.t('common.form.type.planTime')}：</label>
          { formatDate(planTime, DateFormatEnum.YTMHMS) || '--' }
        </div>
        {  this.showModifyPlanTime && (
          <biz-modify-plan-time
            enableSendSms={this.enableSendSms}
            field={this.planTimeField}
            modifiable={allowModifyPlanTimeJudgeHandler(this.task)}
            task={this.task}
            onSuccess={(planTime: string) => this.planTimeChangedHandler(planTime)}
          />
        )}
      </p>
    )
  }

  render(h: CreateElement) {
    const {
      customerName = '',
      customerId = '',
      description = '',
      taskId,
      taskNo = '',
      linkMan,
      address,
      planTime = '',
      serviceContent = '',
      serviceType = '',
      isTimeout,
    } = this.taskMapInfoData
    const classNames = [ComponentNameEnum.TaskMapInfoWindow, this.show ? 'no-position' : 'hidden']
    
    return (
      <div>
        <div class='map-info-window-content map-task-content-window'>
          <div class='map-task-content-window-header'>
            <div 
              class={['customer-name', this.allowCustomerAuth && 'link-text']} 
              onClick={() => this.customerViewJump(customerId)}
            >
              { customerName || '' }
            </div>
            {isTimeout && (
              <ui-task-state task={this.task}>
              </ui-task-state>
            )}
            {/* {this.showCloseButton && (
              <button type='button' class='task-map-info-window-close' onClick={() => this.closedHandler()}>
                <i class='iconfont icon-fe-close'></i>
              </button>
            )} */}
            {this.renderTaskMapInfoWindowHeader && (
              this.renderTaskMapInfoWindowHeader(this.taskMapInfoData)
            )}
          </div>
          {taskNo && (
            <p>
              <label>{i18n.t('common.form.type.taskNo')}：</label>
              <span 
                class={{ 'link-text': this.globalIsHaveTaskViewDetailAuth }} 
                onClick={() => {
                  if (!this.globalIsHaveTaskViewDetailAuth) return
                  openTabForTaskView(taskId)
                }}
              >
                { taskNo }
              </span>
            </p>
          )}
          <p>
            <label>{i18n.t('common.base.contact')}：</label>
            <span>{ linkMan.name || '' }</span>
          </p>
          <p class="flex-x jus-bet">
            <div>
              <label>{i18n.t('common.base.phone')}：</label>
              { linkMan.phone || '' }
            </div>
            <biz-call-center-phone phone={linkMan.phone} />
          </p>
          { this.renderSystemField(true, i18n.t('common.base.address') as string, fmt_address(address)) }

          { !isCalendar && this.renderPlanDate(planTime) }
          { isCalendar && this.renderCalendarDate() }

          { this.renderSystemField(this.isHaveServiceTypeField, i18n.t('common.form.type.serviceType') as string, serviceType) }
          { this.renderSystemField(this.isHaveServiceTypeField, i18n.t('common.form.type.serviceContent') as string, serviceContent) }
          { this.renderSystemField(this.isHaveLevelField, i18n.t('common.form.type.description') as string, description) }
          {/* <div class='info-window-arrow'></div> */}
        </div>
      </div>
    )
  }
  
}

